$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'sys/user/list',
        datatype: "json",
        colModel: [
            { label: '用户ID', name: 'userId', hidden: true, index: "user_id", width: 45, key: true },
            { label: '用户名', name: 'username', width: 75 },
            { label: '工号', name: 'num', width: 40 },
            { label: '所属部门', name: 'deptName', sortable: false, width: 75 },
            /*{ label: '邮箱', name: 'email', width: 90 },
            { label: '手机号', name: 'mobile', width: 100 },*/
            { label: '状态', name: 'status', width: 60, formatter: function(value, options, row){
                    return value === 0 ?
                        '<span class="label label-danger">禁用</span>' :
                        '<span class="label label-success">正常</span>';
                }},
            { label: '创建时间', name: 'createTime', index: "create_time", width: 85}
        ],
        viewrecords: true,
        height: 385,
        rowNum: 10,
        rowList : [10,30,50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page",
            rows:"limit",
            order: "order"
        },
        gridComplete:function(){
            //隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
        }
    });
});
var setting = {
    /*ztree多选：
     * check: {
        enable: true,
        chkStyle: "checkbox",
        chkboxType: { "Y": "s", "N": "ps" }
    },*/
    data: {
        simpleData: {
            enable: true,
            idKey: "deptId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url:"nourl"
        }
    }
};
var ztree;
Vue.component('v-select', VueSelect.VueSelect);
var vm = new Vue({
    el:'#rrapp',
    data:{
        q:{
            username: null
        },
        showList: true,
        title:null,
        roleList:{},
        user:{
            status:1,
            deptName:null,
            roleIdList:[],
            deptIdList:[]
        },
        options: {},
        placeholder: '请选择职称',
        /*posits: []下拉列表可以多选*/
        posits: null
    },
    methods: {
        query: function () {
            vm.reload();
        },
        add: function(){
            vm.showList = false;
            vm.title = "新增";
            vm.roleList = {};
            vm.user = {deptName:null,deptIdList:[], status:1, roleIdList:[]};

            vm.getDept();
            //vm.getPosit();
        },
       /* getPosit: function(){
            $.get(baseURL + "sys/dict/positList", function(r){

            })
        },*/
        getDept: function(){
            //加载部门树
            $.get(baseURL + "sys/dept/list", function(r){
                ztree = $.fn.zTree.init($("#deptTree"), setting, r);

                //ztree多选去掉父节点选框
                /* var allNodes=ztree.getNodes();这里只能找到最外层所有的节点
              if(allNodes.length>0){
                  for(var i=0;i<allNodes.length;i++){
                      if(allNodes[i].isParent){//找到父节点
                          allNodes[i].nocheck=true;//nocheck为true表示没有选择框
                      }
                  }
              }*/

                var deptIdLen = vm.user.deptIdList.length;
                if(deptIdLen > 0){
                    for(var i =0;i<deptIdLen;i++){
                        var node =ztree.getNodeByParam("deptId",vm.user.deptIdList[i],null);
                        if(node != null){
                            ztree.selectNode(node);
                            // ztree多选：ztree.checkNode(node, true, true);
                        }
                    }
                }

            })
        },
        update: function () {
            var userId = getSelectedRow();
            if(userId == null){
                return ;
            }

            vm.showList = false;
            vm.title = "修改";

            vm.getUser(userId);
            //获取角色信息
            vm.getRoleList();
        },
        permissions: function () {
            var userId = getSelectedRow();
            if(userId == null){
                return ;
            }

            window.location.href=baseURL+"sys/permissions/index/"+userId;
        },
        del: function () {
            var userIds = getSelectedRows();
            if(userIds == null){
                return ;
            }
            confirm('确定要删除选中的记录？', function(){
                $.ajax({
                    type: "POST",
                    url: baseURL + "sys/user/delete",
                    contentType: "application/json",
                    data: JSON.stringify(userIds),
                    success: function(r){
                        if(r.code == 0){
                            alert('操作成功', function(){
                                vm.reload();
                            });
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        saveOrUpdate: function () {
            var url = vm.user.userId == null ? "sys/user/save" : "sys/user/update";
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: JSON.stringify(vm.user),
                success: function(r){
                    if(r.code === 0){
                        alert('操作成功', function(){
                            vm.reload();
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        getUser: function(userId){
            $.get(baseURL + "sys/user/info/"+userId, function(r){
                vm.user = r.user;
                vm.user.password = null;
                vm.getDept();
                vm.getRoleList(vm.user.deptId);
            });
        },
        getRoleList: function(deptId){
            $.get(baseURL + "sys/role/select/"+deptId, function(r){
                vm.roleList = r.list;
            });
        },
        deptTree: function(){
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择部门",
                area: ['300px', '450px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#deptLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = ztree.getSelectedNodes();
                    /* ztree多选提交
                     * var node = ztree.getCheckedNodes();
                     * var deptNames='';
                     var arr = [];
                     $.each(node, function(i,v){
                         arr.push(v.deptId);
                         deptNames += v.name +',';
                     });
                     vm.user.deptIdList=arr;
                     vm.user.deptName = deptNames.substring(0,deptNames.length-1);*/
                    //选择上级部门
                    vm.user.deptId = node[0].deptId;
                    vm.user.deptName = node[0].name;

                    layer.close(index);
                    //获取角色信息
                    vm.getRoleList(vm.user.deptId);
                }
            });
        },
        reload: function () {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam','page');
            $("#jqGrid").jqGrid('setGridParam',{
                postData:{'username': vm.q.username},
                page:page
            }).trigger("reloadGrid");
        }
    }
});